// components/signature/signature.js
// canvas 全局配置
var context = null; // 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;
var arrx = [];
var arry = [];
var arrz = [];
var canvasw = 0;
var canvash = 0;

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    open: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    openSignature() {
      this.setData({
        open: true
      })

      //获取系统信息
      wx.getSystemInfo({
        success: function(res) {
          canvasw = res.windowWidth; //设备宽度
          canvash = res.windowWidth * 7 / 15;
        }
      });

      // 使用 wx.createContext 获取绘图上下文 context
      context = wx.createCanvasContext('canvas', this);
      context.beginPath()
      context.setStrokeStyle('#000000');
      context.setLineWidth(4);
      context.setLineCap('round');
      context.setLineJoin('round');
    },

    colse() {
      this.clearDraw();
      context = null;
      isButtonDown = false;
      canvasw = 0;
      canvash = 0;

      this.setData({
        open: false
      })
    },

    /**
     * 藜取签名图片
     */
    getImg() {
      if (arrx.length == 0) {
        wx.showModal({
          title: '提示',
          content: '签名内容不能为空！',
          showCancel: false
        });
        return false;
      }

      let that = this;
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        fileType: 'png',
        quality: 1, //图片质量
        success(res) {
          that.triggerEvent('getSignature', res.tempFilePath)
          that.colse();
        }
      }, this)
    },

    canvasIdErrorCallback: function(e) {
      console.error(e.detail.errMsg)
    },
    canvasStart: function(event) {
      isButtonDown = true;
      arrz.push(0);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);

    },
    canvasMove: function(event) {
      if (isButtonDown) {
        arrz.push(1);
        arrx.push(event.changedTouches[0].x);
        arry.push(event.changedTouches[0].y);
      };

      for (var i = 0; i < arrx.length; i++) {
        if (arrz[i] == 0) {
          context.moveTo(arrx[i], arry[i])
        } else {
          context.lineTo(arrx[i], arry[i])
        };

      };
      context.clearRect(0, 0, canvasw, canvash);

      context.setStrokeStyle('#000000');
      context.setLineWidth(3);
      context.setLineCap('round');
      context.setLineJoin('round');
      context.stroke();

      context.draw(false);
    },
    canvasEnd: function(event) {
      isButtonDown = false;
    },
    clearDraw: function() {
      //清除画布
      arrx = [];
      arry = [];
      arrz = [];
      context.clearRect(0, 0, canvasw, canvash);
      context.draw();
    }
  }
})